<?php

namespace App\Service\VendorClient\Shopfangxingou;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * 放心购上游对接
 * @author: hj
 */
class ShopfangxingouApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shopfangxingou';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //优惠
        $discount_money = $orderInfo['discount_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //用户实际支付金额
        $real_total_money = $orderInfo['real_total_money'];
        //支付公司和电商平台
        $payCommanyCode = isset($apply_extends['payCommanyCode']) && !empty($apply_extends['payCommanyCode']) ? $apply_extends['payCommanyCode'] : '';
        $payCommanyCode = isset($order['payCommanyCode']) && !empty($order['payCommanyCode']) ? $order['payCommanyCode'] : $payCommanyCode;
        $paySerial      = isset($apply_extends['paySerial']) && !empty($apply_extends['paySerial']) ? $apply_extends['paySerial'] : '';
        $paySerial      = isset($order['paySerial']) && !empty($order['paySerial']) ? $order['paySerial'] : $paySerial;
        $enterpriseNum  = isset($apply_extends['enterpriseNum']) && !empty($apply_extends['enterpriseNum']) ? $apply_extends['enterpriseNum'] : '';
        $enterpriseNum  = isset($order['enterpriseNum']) && !empty($order['enterpriseNum']) ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = isset($apply_extends['enterpriseName']) && !empty($apply_extends['enterpriseName']) ? $apply_extends['enterpriseName'] : '';
        $enterpriseName = isset($order['enterpriseName']) && !empty($order['enterpriseName']) ? $order['enterpriseName'] : $enterpriseName;
        //获取下单商品信息
        $palceOrderGoods    = [];
        $totalGoodsMoney    = '0.00';
        $goodsTotalMoney    = '0.00';
        $goodsTotalMoneyNot = '0.00';
        $wayTaxFee          = '0.00';
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;
            if ($key == 0) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money, (string)$quantity, 3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney, (string)100, 1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100, 2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney, 2);
            }
            //单个商品价格
            $singleGoodsPrice = bcdiv((string)$price, (string)$spec_num, 3);
            $singleGoodsPrice = ceil(bcmul((string)$singleGoodsPrice, (string)'100', 1));
            $singleGoodsPrice = bcdiv((string)$singleGoodsPrice, '100', 2);
            $totalGoods       = bcmul((string)$singleGoodsPrice, (string)$buyAcount, 2);

            //含税税率
            $tax_rate = bcadd('1', (string)$item['tax_rate'], 4);
            //不含税价格
            $not_tax_price = bcdiv((string)$singleGoodsPrice, $tax_rate, 3);
            //echo "含税单价:".$singleGoodsPrice."含税税率:".$tax_rate."不含税价格：".$not_tax_price;
            $not_tax_price = ceil(bcmul((string)$not_tax_price, '100', 1));
            // echo "含税税率:".$tax_rate."不含税价格：".$not_tax_price;
            $not_tax_price = bcdiv((string)$not_tax_price, '100', 2);

            //不含税总价
            $goodsTotalPrice = bcmul((string)$not_tax_price, (string)$buyAcount, 2);

            //税金
            $singleGoodsTax = bcsub((string)$singleGoodsPrice, (string)$not_tax_price, 3);
            $taxAll         = bcmul($singleGoodsTax, (string)$buyAcount, 2);
            //不含税总金额
            $goodsTotalMoneyNot = bcadd((string)$goodsTotalMoneyNot, $goodsTotalPrice, 2);
            //含税总金额
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, $totalGoods, 2);
            //总税费
            $wayTaxFee = bcadd((string)$wayTaxFee, $taxAll, 2);
            //下单商品组
            $goodsInfo         = [
                // 'item_code'    => trim($item['supplier_commodity_key']),//商品编码 可以传空
                'item_code'    => '',//商品编码 可以传空
                // 'price'        => (float)$singleGoodsPrice,//商品采购价（单位：元）
                'price'        => (float)$not_tax_price,//商品采购价（单位：元）
                'quantity'     => (int)$buyAcount,//商品数量
                'spec_name'    => $item['spec_name'],//商品规格名称（计量单位）
                'custom_price' => (float)$taxAll,//商品关税  Price*quantity*关税比例
                'name'         => $item['goods_name'],//商品名称
                'supply_price' => (float)$item['costprice'],//商品结算价格
                'sku_no'       => trim($item['supplier_skucode']),//商品规格编号
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        $calTotal = bcadd($goodsTotalMoneyNot, $wayTaxFee, 2);
        $couponFee    = $calTotal > $orderInfo['real_total_money'] ? bcsub($calTotal, $orderInfo['real_total_money'], 2) : '0.00';
        $requestParam = [
            'app_key'         => $this->config['appKey'],
            'version'         => '1.0',
            'order_no'        => $order_sn,//订单号
            'order_time'      => $order_time,//下单时间
            'pay_time'        => $pay_time,//支付时间
            'pay_type'        => $payCommanyCode,//支付类型  传支付企业的海关代码
            'pay_amount'      => (float)$orderInfo['real_total_money'],//支付金额
            'pay_code'        => $paySerial,//支付交易号
            'ent_code'        => $enterpriseNum,//电商平台编码
            'ent_name'        => $enterpriseName,//电商平台名称
            'order_desc'      => $orderInfo['order_remark'] ?? '',//订单备注
            'tax_amount'      => (float)$wayTaxFee,//税费
            'ship_name'       => $orderInfo['receive_name'],//收件人
            'ship_mobile'     => $orderInfo['recveive_phone'],//收件人手机号
            'id_card'         => $orderInfo['buyer_idcard'],//收件人身份证号码
            'ship_province'   => $orderInfo['province'],//省
            'ship_city'       => $orderInfo['city'],//市
            'ship_area'       => $orderInfo['district'],//区、县
            'ship_address'    => $orderInfo['receive_address'],//具体地址
            'discount_amount' => (float)$couponFee,//优惠减免金额
            'buy_name'        => $orderInfo['buyer_realname'],//支付人名称
            'buy_id'          => $orderInfo['buyer_idcard'],//支付人身份证号
            'express_name'    => '',//快递公司名称
            'express_code'    => '',//快递公司编码
            'freight'         => 0.00,//运费
            'source'          => $this->config['source'],//来源
            'goods_data'      => $palceOrderGoods,//商品数据的json串
        ];
        $data         = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        $result       = $this->execute($data);
        if (isset($result['success']) && $result['success'] == true) {
            return Normal::returnCode(Normal::SUC, "推单成功", $result);
        } else {
            $msg = $result['msg'] ?? '推单失败';
            return Normal::returnCode(Normal::FAIL, $msg, $result);
        }
    }

    /**
     * 查询物流
     * @param $orderSupplier
     * @return array
     */
    public function queryOrderExpress($orderSupplier) {
        $orderSn = $orderSupplier['supplier_dsn'];
        $data    = [
            'method' => 'orderExpress',
            'data'   => [
                'app_key'  => $this->config['appKey'],
                'order_no' => json_encode([$orderSn], JSON_UNESCAPED_UNICODE),//订单号
            ],
        ];
        $result  = $this->execute($data);
        if (isset($result['code']) && $result['code'] == 200) {
            //成功
            $expressList = $result['orders'] ?? [];
            if (empty($expressList)) {
                return Normal::returnCode(Normal::FAIL, '未查询到物流信息1', $result);
            }
            $expressListByOrderSn = array_column($expressList, NULL, 'order_no');
            $expressArr           = $expressListByOrderSn[$orderSn] ?? [];
            if (empty($expressArr)) {
                return Normal::returnCode(Normal::FAIL, '未查询到物流信息2', $result);
            }
            return Normal::returnCode(Normal::SUC, "获取成功", $expressArr);
        } else {
            $msg = $result['msg'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg, $result);
        }
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        $str = $this->config['appKey'] . $data['order_no'] . $this->config['apiSecret'];
        //md5(key+order_no+ApiSecret)
        return md5($str);
    }

    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        if (!isset($this->config[$param['method']])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $baseUrl = $this->config['baseUrl'];
        if (empty($baseUrl)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $url              = $baseUrl . $this->config[$param['method']];
        $pushData         = $param['data'];
        $pushData['sign'] = $this->sign($pushData);
        $parameter        = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'json',
                'header' => [],
            ],
        ];
        if (in_array($param['method'], ['orderExpress'])) {
            $resTask = TaskWorker::instance()->addTask($parameter, 'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        return @json_decode($resTask['response']['result'], true);
    }


}